from flask import Blueprint, jsonify, request
from app import mysql
from functools import wraps

# 创建主蓝图
main_bp = Blueprint('main', __name__)

from flask import Blueprint
routes_bp = Blueprint('routes', __name__)

def handle_db_error(f):
    """数据库错误处理装饰器"""
    @wraps(f)
    def wrapper(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except Exception as e:
            mysql.connection.rollback()
            return jsonify({
                'success': False,
                'message': '数据库操作失败',
                'error': str(e)
            }), 500
    return wrapper

@main_bp.route('/')
def index():
    """健康检查端点"""
    return jsonify({
        'status': 'API is running',
        'version': '1.0',
        'routes': {
            'index': '/',
            'test': '/test',
            'echo': '/echo (POST)'
        }
    })

@main_bp.route('/test')
def test_route():
    """测试端点"""
    return jsonify({
        'success': True,
        'message': '测试端点正常工作',
        'data': {
            'service': 'Flask API',
            'status': 'active'
        }
    })

@main_bp.route('/echo', methods=['POST'])
def echo():
    """回显请求数据"""
    data = request.get_json()
    return jsonify({
        'success': True,
        'received_data': data,
        'metadata': {
            'method': request.method,
            'content_type': request.content_type
        }
    })

@main_bp.route('/db-check')
@handle_db_error
def db_check():
    """数据库连接检查"""
    cursor = mysql.connection.cursor()
    cursor.execute("SELECT 1")
    result = cursor.fetchone()
    cursor.close()
    return jsonify({
        'success': True,
        'database': 'connected',
        'result': result[0]
    })

# 示例受保护路由
@main_bp.route('/protected')
def protected_route():
    """示例受保护路由（需要JWT验证）"""
    # 实际应用中这里应该检查JWT
    auth_header = request.headers.get('Authorization')
    if not auth_header or not auth_header.startswith('Bearer '):
        return jsonify({
            'success': False,
            'message': '未授权的访问'
        }), 401
        
    return jsonify({
        'success': True,
        'message': '您已访问受保护资源',
        'user': {
            'access_level': 'admin'
        }
    })